package com.weimob.mcloud.wechatwork.customer.mq.userPermission.handler.logicHandler;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.common.utils.CollUtils;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.group.CustomerGroup;
import com.weimob.mcloud.wechatwork.core.service.group.dto.GroupVidDTO;
import com.weimob.mcloud.wechatwork.core.service.group.request.GroupManagedVidDTO;
import com.weimob.mcloud.wechatwork.customer.mq.userPermission.dto.EmployeeVidsDTO;
import com.weimob.mcloud.wechatwork.customer.third.PrivateSphereThird;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerGroupExportServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 处理客户群的权限变更消息（更新客户群的权限字段）
 * 客户群目前只会有两种消息场景：
 * type 1：员工级别的权限变更消息
 * type 3：corpId级别的权限变更消息，需要将该corpId下的所有员工的vidList都更新到其下所有客户群权限字段中
 *
 * @Author LeoLee
 * @Date 2022/8/23 16:06
 * @Version 1.0
 */

@Slf4j
@Component
public class GroupChatUserPermissionHandler implements PermisssionChangeHandler {

    @Value("${group.permission.partition.size:10}")
    private int partitionSize;

    @Resource
    private PrivateSphereThird privateSphereThird;

    @Resource
    private CustomerGroupExportServiceProxy customerGroupExportServiceProxy;

    @Override
    public void updatePermission(List<? extends EmployeeVidsDTO> employeeVidsDTOS, Integer msgType) {
        log.info("客户群员工数据隔离范围变化，employeeVidsDTOS:{},msgType:{}", JSON.toJSONString(employeeVidsDTOS),msgType);
        String corpId = employeeVidsDTOS.get(0).getCorpId();
        // 查私域
        PrivateSphere privateSphere = privateSphereThird.fetch(corpId);

        Map<String, List<Long>> employeeIdVidsMap = CollUtils.toMap(employeeVidsDTOS, EmployeeVidsDTO::getEmployeeId, EmployeeVidsDTO::getVidList);
        List<String> employeeIdList = CollUtils.map(employeeVidsDTOS, EmployeeVidsDTO::getEmployeeId);
        // 1、获取全部客户群
        List<CustomerGroup> allCustomerGroup = new ArrayList<>();
        List<List<String>> partition = Lists.partition(employeeIdList, partitionSize);
        for (List<String> employeeIds : partition) {
            int pageNum = 1;
            int pageSize = 100;
            HashMap<String, Object> extInfo = new HashMap<>();
            extInfo.put("orderBy", "id");
            extInfo.put("direction", "asc");
            CustomerGroup customerGroup = new CustomerGroup();
            customerGroup.setPrivateSphere(privateSphere);
            MultiResponse<CustomerGroup> multiResponse;
            do {
                multiResponse = customerGroupExportServiceProxy.fetchCustomerGroupListES(customerGroup, true,
                        false, pageNum, pageSize, extInfo, employeeIds, null, null, null,false);
                List<CustomerGroup> dataList = multiResponse.getDataList();
                if (!CollectionUtils.isEmpty(dataList)) {
                    allCustomerGroup.addAll(dataList);
                }
                pageNum++;
            } while (Objects.nonNull(multiResponse.getTotalPage()) && pageNum <= multiResponse.getTotalPage());
        }
        // 2、更新客户群managedVid
        List<List<CustomerGroup>> groupPartition = Lists.partition(allCustomerGroup, 500);
        for (List<CustomerGroup> customerGroupList : groupPartition) {
            List<GroupVidDTO> groupVidList = new ArrayList<>(customerGroupList.size());
            for (CustomerGroup customerGroup : customerGroupList) {
                GroupVidDTO groupVidDTO = new GroupVidDTO();
                groupVidDTO.setCorpId(customerGroup.getCorpId());
                groupVidDTO.setPrivateSphere(privateSphere);
                groupVidDTO.setGroupId(customerGroup.getGroupId());
                List<Long> vidList = employeeIdVidsMap.get(customerGroup.getOwner().getId());
                groupVidDTO.setVidList(vidList);
                groupVidList.add(groupVidDTO);
            }
            GroupManagedVidDTO groupManagedVidDTO = new GroupManagedVidDTO();
            groupManagedVidDTO.setGroupVidList(groupVidList);
            customerGroupExportServiceProxy.batchSaveGroupManagedVid(groupManagedVidDTO);
        }

    }
}
